package jmine.tec.utils.cripto.key.impl;

import java.security.KeyPair;
import java.security.PrivateKey;
import java.security.PublicKey;

import jmine.tec.utils.cripto.key.GeradorChaveRSA;
import jmine.tec.utils.cripto.key.KeyPairHolder;


import org.springframework.beans.factory.InitializingBean;
import org.springframework.core.io.Resource;

/**
 * @author takeshi
 */
public class StaticKeyPairHolder implements KeyPairHolder, InitializingBean {

    private Resource publicKeyResource, privateKeyResource;

    private volatile KeyPair keyPair;

    /**
     * {@inheritDoc}
     */
    public KeyPair get() {
        return keyPair;
    }

    /**
     * @return the publicKeyResource
     */
    public Resource getPublicKeyResource() {
        return publicKeyResource;
    }

    /**
     * @param publicKeyResource the publicKeyResource to set
     */
    public void setPublicKeyResource(Resource publicKeyResource) {
        this.publicKeyResource = publicKeyResource;
    }

    /**
     * @return the privateKeyResource
     */
    public Resource getPrivateKeyResource() {
        return privateKeyResource;
    }

    /**
     * @param privateKeyResource the privateKeyResource to set
     */
    public void setPrivateKeyResource(Resource privateKeyResource) {
        this.privateKeyResource = privateKeyResource;
    }

    /**
     * {@inheritDoc}
     */
    public void afterPropertiesSet() throws Exception {
        PublicKey publicKey = GeradorChaveRSA.leChavePublica(this.publicKeyResource.getInputStream());
        PrivateKey privateKey = GeradorChaveRSA.leChavePrivada(this.privateKeyResource.getInputStream());
        this.keyPair = new KeyPair(publicKey, privateKey);
    }

}
